/*
 * client.c
 *
 *  Created on: May 3, 2011
 *      Author: tvale, dmourao
 */
#include "common.h"
#include "client.h"
#include <mpi.h>
#include <stdlib.h>

/*
 * Client state.
 *      my_rank:  self explainable;
 *      srv_rank: private server's rank.
 */
static int my_rank;
static int srv_rank;

/*
 * Operations.
 */
static int
get()
{
  int var;

  MPI_Send(NULL, 0, MPI_INT, srv_rank, MSG_GET_CLT, MPI_COMM_WORLD      );
  MPI_Recv(&var, 1, MPI_INT, srv_rank, MSG_GET_SRV, MPI_COMM_WORLD, NULL);

  return var;
}

static void
set(int value)
{
  msg_t msg = {
      .type = MSG_SET,
      .payload = {
          .value = value
      }
  };
  MPI_Send(&msg, 1, MPI_MESSAGE, srv_rank, MSG_SET, MPI_COMM_WORLD);
}

void
client_main(int r, int n_writes)
{
  my_rank  = r;
  srv_rank = my_rank - 1;

  srand(my_rank);
  for (int i = 0; i < n_writes; i++)
    set(rand());

  MPI_Send(NULL, 0, MPI_INT, srv_rank, MSG_STOP_CLT, MPI_COMM_WORLD);
}
